package com.qk.management.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.entity.Dept;
import com.qk.entity.User;
import com.qk.management.mapper.DeptMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: zyx
 * @created: 2025-09-29-10:39
 * @description:
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Dept getById(Integer id) {
        Dept dept =deptMapper.selectByID(id);
        return dept;
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateById(dept);
    }

    @Override
    public void delete(Integer id) {
        //拿到部门下的所有用户列表，如果存在用户则不允许删除
        List<User> users = userMapper.selectList(Wrappers.<User>lambdaQuery().eq(User::getDeptId, id));
        if(!users.isEmpty()){
            CommonException.throwCommonException(ParamEnum.REFERENCE_ERROR);
        }
        deptMapper.deleteById(id);
    }

    @Override
    public List<Dept> getAllDepts() {
        return deptMapper.selectAll();
    }

    @Override
    public PageResult<Dept> page(String name, Integer status, Integer page, Integer pageSize) {
        //查询满足条件总记录数
        Integer total = deptMapper.count(name, status);
        //查询分页数据
        Integer offSet = (page - 1) * pageSize;
        List<Dept> rows = deptMapper.selectByPage(name, status, offSet, pageSize);
        //打包成PageResult对象并返回
        return PageResult.<Dept>builder().total(total).rows(rows).build();
    }


    @Override
    public void addDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }


}
